﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using HZ.BidSystem.Model;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;

public partial class Company_BidPrice : System.Web.UI.Page, IAccess
{
    string action = string.Empty;
    string msg2 = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        action = Request.QueryString["action"] == null ? "bid" : Request.QueryString["action"].ToLower();
        CurrentAccount.CheckSessionTimeOut(this);
        // 验证报价密码
        if (!CurrentAccount.IsCheckBidPwd)
        {
            Response.Redirect(string.Format("CheckBidPwd.aspx?action={0}", action));
        }

        if (CurrentAccount.IsConfirmBid)
        {
            Response.Redirect(string.Format("PrePrintPrice.aspx?action={0}", action));
        }

        // 报价时间到 直接进入确认
        if (CurrentProject.InBidTime > 0)
        {
            //Response.Redirect(string.Format("ConfirmBid.aspx?action={0}", action));
            // HZ.Web.MessageBox.Show("报价时间已到！");
        }

        if (!CurrentProject.IsBidSwitch)
        {
            HZ.Web.MessageBox.Show("报价开关未开启，暂时无法报价。");
        }

        ////if (CurrentProject.InBidTime < 0)
        ////{
        ////    HZ.Web.MessageBox.Show("报价时间未到，请稍后！");
        ////}


        if (!IsPostBack)
        {
            bidinfo.Text = BLL_Factory.IBLL_Manage.GetConfigurationByKey("BidDes").Value;
            BindData();

            ViewState["CompanyId"] = CurrentAccount.Account.AccountId.Value;
            HZ.BidSystem.BLL.BLL_Cache.SetOnlineModel(CurrentAccount.Account.AccountId.Value, new OnLineModel() { Active = "正在认真报价" });

            if (HttpContext.Current.Request["isbid"] != null)
            {
                if (HttpContext.Current.Request["isbid"].ToString() == "2")
                {
                    ToSure.Visible = true;
                }
            }
        }

        if (IsPostBack)
        {
            if ((int)ViewState["CompanyId"] != CurrentAccount.Account.AccountId.Value)
            {

                Response.Redirect("~/Timeout.htm");
            }

        }
        WebTimer1.EndTime = CurrentProject.ProjectConfig.BidEndTime.Value;
        WebTimer1.BeginTime = CurrentProject.ProjectConfig.BidStartTime.Value;
    }

    protected void btnSubmitPrice_Click(object sender, EventArgs e)
    {
        //int countZone = 0;
        //string zonecheck = "";
        //for (int i = 0; i < gvbidprice.Rows.Count; i++)
        //{
        //        //获取提交状态
        //    Label clickstatus = (Label)gvbidprice.Rows[i].FindControl("lab_Zone_Count");
        //    if (clickstatus.Text.Trim()!="0")
        //        {
        //            countZone += 1;
        //        }
        //}
        if (CurrentProject.InBidTime < 0)
        {
            HZ.Web.MessageBox.Show("报价时间未到，请稍后！");
            return;
        }
        // 报价时间到 直接进入确认
        if (CurrentProject.InBidTime > 0)
        {
            //Response.Redirect(string.Format("ConfirmBid.aspx?action={0}", action));
            HZ.Web.MessageBox.Show("报价时间已过！");
            return;
        }

        IList<int> bidids = new List<int>();
        IList<double> bidprices = new List<double>();
        IList<int> A_Zone = new List<int>();//A区
        IList<int> B_Zone = new List<int>();//B区
        IList<int> C_Zone = new List<int>();//C区
        IList<int> D_Zone = new List<int>();//D区
        IList<int> E_Zone = new List<int>();//E区
        //IList<int> F_Zone = new List<int>();//F区
        string errorgoodslist = "";
        lblmsg2.Visible = false;
        lblmsg2.Text = "";
        string strSQL = "";
        //高于限价次数
        int highPriceNum = 0;
        //输入的数据有错误
        int errorNum = 0;
        foreach (GridViewRow item in gvbidprice.Rows)
        {

            if (item.RowType == DataControlRowType.DataRow)
            {
                string strprice = (item.FindControl("txtBidPrice") as TextBox).Text;
                string strOldPrice = (item.FindControl("txtOldPrice") as HiddenField).Value;


                CheckBox azone = (CheckBox)item.FindControl("cb_A");
                CheckBox bzone = (CheckBox)item.FindControl("cb_B");
                CheckBox czone = (CheckBox)item.FindControl("cb_C");

                CheckBox dzone = (CheckBox)item.FindControl("cb_D");
                CheckBox ezone = (CheckBox)item.FindControl("cb_E");
                //CheckBox fzone = (CheckBox)item.FindControl("cb_F");
                string Company_Goods = item.Cells[2].Text;
                string strLimitPrice = (item.FindControl("LimitPrice") as Label).Text;  //限价
                string strOnePrice = (item.FindControl("LimitOneBidPrice") as Label).Text;  //2011年中标价
                string strTwoPrice = (item.FindControl("LimitTwoBidPrice") as Label).Text;  //约束价
                string strRetailPrice = (item.FindControl("RetailPrice") as Label).Text; //政府定价
                string Factor = (item.FindControl("lblFactor") as Label).Text;               //转换系数 

                if (HZ.Fun.IsUFloat(strprice) && new HZ.Common.ConvertHelper(strprice).ToDouble.HasValue)
                {
                    Label clickstatus = (Label)item.FindControl("lab_Zone_Count");//读取报价区域个数
                    //如果报价区域为0时，可以不勾选报价区域直接报价，否则至少要勾选一个报价区域

                    if (clickstatus.Text.Trim() == "0" || azone.Checked == true || bzone.Checked == true || czone.Checked == true)
                    {
                        var bidid = new HZ.Common.ConvertHelper(item.Cells[0].Text).ToInt32;
                        if (bidid == null)
                        {
                            continue;
                        }
                        else
                        {
                            string Regextest = "^[0-9]+(\\.[0-9]{1,2})?$";
                            if (!Regex.IsMatch(strprice, Regextest))
                            {

                                lblmsg2.Text += "流水号为" + Company_Goods + "的品规，报价小数点不能超过2位！";
                                lblmsg2.Visible = true;
                                errorNum++;
                                continue;
                            }
                            //不检测是否高于限价 by yjx 2016年8月16日 13:05:56
                            if (System.Configuration.ConfigurationManager.AppSettings["IsToComparePrice"].ToString() != "0")
                            {
                                if (!string.IsNullOrEmpty(strLimitPrice) && (Convert.ToDecimal(strprice)) > Convert.ToDecimal(strLimitPrice))
                                {
                                    lblmsg2.Text += "流水号为" + Company_Goods + "的品规，高于限价！";
                                    lblmsg2.Visible = true;
                                    highPriceNum++;
                                    //阻止报价高于限价的产品更新
                                    if (System.Configuration.ConfigurationManager.AppSettings["IsToComparePrice"].ToString() == "1")
                                    {
                                        continue;
                                    }
                                }

                                if (!string.IsNullOrEmpty(strRetailPrice) && (Convert.ToDecimal(strprice)) > Convert.ToDecimal(strRetailPrice))
                                {
                                    lblmsg2.Text += "流水号为" + Company_Goods + "的品规，高于最小包装单位政府定价(或企业自主定价)的批发价！";
                                    lblmsg2.Visible = true;
                                    highPriceNum++;
                                    //阻止报价高于限价的产品更新
                                    if (System.Configuration.ConfigurationManager.AppSettings["IsToComparePrice"].ToString() == "1")
                                    {
                                        continue;
                                    }
                                }
                                if (!string.IsNullOrEmpty(strOnePrice) && (Convert.ToDecimal(strprice)) > Convert.ToDecimal(strOnePrice))
                                {
                                    lblmsg2.Text += "流水号为" + Company_Goods + "的品规，高于中标价！";
                                    lblmsg2.Visible = true;
                                    highPriceNum++;
                                    //阻止报价高于限价的产品更新
                                    if (System.Configuration.ConfigurationManager.AppSettings["IsToComparePrice"].ToString() == "1")
                                    {
                                        continue;
                                    }
                                }
                                if (!string.IsNullOrEmpty(strTwoPrice) && (Convert.ToDecimal(strprice)) > Convert.ToDecimal(strTwoPrice))
                                {
                                    lblmsg2.Text += "流水号为" + Company_Goods + "的品规，高于约束价！";
                                    lblmsg2.Visible = true;
                                    highPriceNum++;
                                    //阻止报价高于限价的产品更新
                                    if (System.Configuration.ConfigurationManager.AppSettings["IsToComparePrice"].ToString() == "1")
                                    {
                                        continue;
                                    }
                                }
                            }
                            bidids.Add(bidid.Value);
                            bidprices.Add(new HZ.Common.ConvertHelper(strprice).ToDouble.Value);
                            A_Zone.Add(azone.Checked == true ? 1 : 0);
                            B_Zone.Add(bzone.Checked == true ? 1 : 0);
                            C_Zone.Add(czone.Checked == true ? 1 : 0);
                            //D_Zone.Add(dzone.Checked == true ? 1 : 0);
                            //E_Zone.Add(ezone.Checked == true ? 1 : 0);
                            //F_Zone.Add(fzone.Checked == true ? 1 : 0);


                        }
                    }
                    else
                    {
                        HZ.Web.WebUtil.Alert("可选区域项必须至少一个区域", this);
                        return;
                    }

                }
                else
                {
                    if (!string.IsNullOrEmpty(strprice))
                    {
                        errorgoodslist += Company_Goods + ",";
                        errorNum++;
                    }
                    else if (!string.IsNullOrEmpty(strOldPrice)) //当企业原本有价格，后清空价格时，直接清空历史价格
                    {
                        var bidid = new HZ.Common.ConvertHelper(item.Cells[0].Text).ToInt32;
                        strSQL += string.Format("UPDATE TB_Project_Bid SET EncryptPrice=null WHERE  BidId={0};", bidid);
                        //为了防止大数据提交，导出死锁问题，现不使用表STAT_BidStatus by yjx 2016年8月15日 14:11:23
                        //strSQL += string.Format("update STAT_BidStatus set bidcount= bidcount-1 where usercode = '{0}';", CurrentAccount.Account.AccountName);
                    }
                    continue;
                }
            }
        }
        //为了防止大数据提交，导出死锁问题，现不使用表STAT_BidStatus by yjx 2016年8月15日 14:11:23
        //msg2 = GetBidInfoMsg();
        string msg = lblmsg2.Text.Trim();
        if (errorgoodslist.Length > 0)
        {
            msg += string.Format("流水号为{0}品规 报价格式不是有效报价数字。", errorgoodslist);
            lblmsg2.Text += string.Format("流水号为{0}品规 报价格式不是有效报价数字。", errorgoodslist);
            //return;
        }
        //如果有错误数据，直接不允许提交 by yjx 2016年8月16日 14:02:45
        if (errorNum > 0)
        {
            HZ.Web.WebUtil.Alert(msg, this);
            return;
        }//检测到报价高于限价
        else if (highPriceNum > 0)
        {
            HZ.Web.WebUtil.Alert(lblmsg2.Text.Trim(), this);
            if (System.Configuration.ConfigurationManager.AppSettings["IsToComparePrice"].ToString() != "1")
            {
                if (bidids.Count > 0)
                {
                    try
                    {
                        BLL_Factory.IBLL_Company.BidPrice(bidids, bidprices, A_Zone, B_Zone, C_Zone, D_Zone, E_Zone);
                        HZ.Common.log4netManager.LogInfo("企业提交报价", string.Format("企业提交报价成功：企业编号：{0}，报价IP：{1}，报价产品：{2}。", CurrentAccount.Account.AccountName, CurrentAccount.ClientIP, Util.GetString(bidids)), null);
                        HZ.Web.WebUtil.Alert("保存成功！", this);
                    }
                    catch (Exception ex)
                    {
                        HZ.Common.log4netManager.LogInfo("企业提交报价", string.Format("企业提交报价异常：企业编号：{0}，报价IP：{1}，报价产品：{2}，异常内容：{3}。", CurrentAccount.Account.AccountName, CurrentAccount.ClientIP, Util.GetString(bidids),ex.ToString()), null);
                        HZ.Web.WebUtil.Alert("更新失败，请重新登陆系统！", this);
                    }
                }
            }
        }//当有数据时才会提交报价
        else if (bidids.Count > 0)
        {
            try
            {
                BLL_Factory.IBLL_Company.BidPrice(bidids, bidprices, A_Zone, B_Zone, C_Zone, D_Zone, E_Zone);
                HZ.Common.log4netManager.LogInfo("企业提交报价", string.Format("企业提交报价成功：企业编号：{0}，报价IP：{1}，报价产品：{2}。", CurrentAccount.Account.AccountName, CurrentAccount.ClientIP, Util.GetString(bidids)), null);
                HZ.Web.WebUtil.Alert("保存成功！", this);
            }
            catch (Exception ex)
            {
                HZ.Common.log4netManager.LogInfo("企业提交报价", string.Format("企业提交报价异常：企业编号：{0}，报价IP：{1}，报价产品：{2}，异常内容：{3}。", CurrentAccount.Account.AccountName, CurrentAccount.ClientIP, Util.GetString(bidids), ex.ToString()), null);
                HZ.Web.WebUtil.Alert("更新失败，请重新登陆系统！", this);
            }
        }
        //有清空数据的，直接清空。
        if (strSQL!="")
        {
            try
            {
                HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(strSQL.ToString());
                HZ.Common.log4netManager.LogInfo("企业清空报价", string.Format("企业清空报价成功：企业编号：{0}，报价IP：{1}，报价产品：{2}。", CurrentAccount.Account.AccountName, CurrentAccount.ClientIP, strSQL.ToString()), null);
            }
            catch (Exception ex)
            {
                HZ.Web.WebUtil.Alert("更新失败，请重新登陆系统，再次修改！", this);
            }
        }

        
        BindData();

    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        pager1.CurrentPage = 1;
        BindData();
    }

    protected void BindData()
    {
        int totalrecord;
        string strAppend = "1=1";
        switch (Request.QueryString["isbid"] ?? "0")
        {
            case "1":
                strAppend = " EncryptPrice is null ";
                break;
            case "2":
                strAppend = " EncryptPrice is not null ";
                break;
        }
        var bidprice = BLL_Factory.IBLL_Company.GetBidPriceWithDec(new HZ.BidSystem.Model.QBidPrice() { CompanyId_Tb = CurrentAccount.Account.AccountId.Value, SortFields = "Company_Goods", ProductName = txtProdcutName.Text, Model = txtMedicineModel.Text, Outlookc = txtOutlookc.Text, Append = strAppend }, pager1.CurrentPage, pager1.PageSize, out totalrecord, CurrentAccount.BidPwd, CurrentAccount.RandPwd);
        pager1.RecordCount = totalrecord;

        if (bidprice.Count == 0)
        {
            btnSubmitPrice.Enabled = false;
        }
        else
        {
            btnSubmitPrice.Enabled = true;
        }

        gvbidprice.DataSource = bidprice;
        gvbidprice.DataBind();
        if (msg2 == "")
        {
            //为了防止大数据提交，导出死锁问题，现不使用表STAT_BidStatus by yjx 2016年8月15日 14:11:23
            //msg2 = GetBidInfoMsg();
            lblmsg.Text = msg2;
        }
        else
        {
            lblmsg.Text = msg2;

        }

        //锁定下一页按钮
        JudgeBtn(totalrecord);
    }

    private string GetBidInfoMsg()
    {
        DataTable dt = BLL_Factory.IBLL_Company.GetBidCountByUserCode(CurrentAccount.Account.AccountName);
        if (dt.Rows.Count > 0)
        {
            return string.Format("本次报价产品共{0}个，已提交报价{1}个，未提交报价{2}个", dt.Rows[0]["allcount"], dt.Rows[0]["bidcount"], Convert.ToInt32(dt.Rows[0]["allcount"]) - Convert.ToInt32(dt.Rows[0]["bidcount"]));
        }
        else
        {
            return string.Empty;
        }

    }

    protected void pager1_PageChanging(object sender, HZ.Web.PageChaningEventArgs e)
    {
        BindData();
    }

    /// <summary>
    /// 限价方式
    /// 0 不提示限价
    /// 1 提示限价，但不强制要求
    /// 2 强制要求限价
    /// </summary>
    public int LimitPriceEffectType
    {
        get
        {
            return HZ.BidSystem.Model.SystemConfig.Instance.LimitPriceEffectType;
        }
    }
    #region IAccess Members

    IList<EnumAccess> IAccess.AccessList
    {
        get
        {
            var list = new List<EnumAccess>();
            list.Add(EnumAccess.Company);
            return list;
        }

    }

    #endregion
    protected void gvbidprice_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox txtBidPrice = e.Row.FindControl("txtBidPrice") as TextBox;
            View_BidPrice vb = e.Row.DataItem as View_BidPrice;
            Label lbl = e.Row.FindControl("lbDecPrice2") as Label;
            Label lblFactor = e.Row.FindControl("lblFactor") as Label;

            if (vb.DecPrice.HasValue)
            {

                txtBidPrice.Text = vb.DecPrice.Value.ToString("F" + SystemConfig.Instance.Precision);
                lblFactor.Text = vb.PackFactor.GetValueOrDefault(0).ToString();
                //lbl.Text = (Convert.ToDecimal(txtBidPrice.Text) / Convert.ToDecimal(lblFactor.Text)).ToString("F4");
            }
        }
    }
    protected void ToSure_Click(object sender, EventArgs e)
    {
        Response.Redirect("ConfirmBid.aspx?action=bid");
    }
    /// <summary>
    /// 翻下一页
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_NextPage_Click(object sender, EventArgs e)
    {
        NextPage();
    }

    /// <summary>
    /// 翻下页一页
    /// 为了不影响原先功能
    /// </summary>
    protected void NextPage()
    {
        int totalrecord;
        string strAppend = "1=1";
        switch (Request.QueryString["isbid"] ?? "0")
        {
            case "1":
                strAppend = " EncryptPrice is null ";
                break;
            case "2":
                strAppend = " EncryptPrice is not null ";
                break;
        }
        var bidprice = BLL_Factory.IBLL_Company.GetBidPriceWithDec(new HZ.BidSystem.Model.QBidPrice() { CompanyId_Tb = CurrentAccount.Account.AccountId.Value, SortFields = "Company_Goods", ProductName = txtProdcutName.Text, MedicineModel = txtMedicineModel.Text, Outlookc = txtOutlookc.Text, Append = strAppend }, pager1.CurrentPage + 1, pager1.PageSize, out totalrecord, CurrentAccount.BidPwd, CurrentAccount.RandPwd);
        pager1.RecordCount = totalrecord;


        if (bidprice.Count == 0)
        {
            btnSubmitPrice.Enabled = false;
        }
        else
        {
            btnSubmitPrice.Enabled = true;
        }

        gvbidprice.DataSource = bidprice;
        gvbidprice.DataBind();
        if (msg2 == "")
        {
            //为了防止大数据提交，导出死锁问题，现不使用表STAT_BidStatus by yjx 2016年8月15日 14:11:23
            //msg2 = GetBidInfoMsg();
            lblmsg.Text = msg2;
        }
        else
        {
            lblmsg.Text = msg2;

        }
        //pager的页面显示信息
        pager1.CurrentPage++;

        //锁定下一页按钮
        JudgeBtn(totalrecord);
    }

    /// <summary>
    /// 下一页按钮锁定
    /// </summary>
    /// <param name="total"></param>
    public void JudgeBtn(int total)
    {
        int currentP = pager1.CurrentPage;
        int pageSize = pager1.PageSize;
        if (currentP * pageSize >= total)
        {
            btn_NextPage.Enabled = false;
            btn_NextPage.Text = "当前为最后页";
        }
        else
        {
            btn_NextPage.Text = "下一页";
            btn_NextPage.Enabled = true;
        }
    }
}
